package com.whq.mvc.base.juc;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5);
        for (int i = 0; i < 5; i++) {
            new MyThread(barrier).start();
        }
        System.out.println("主线程执行完成");
    }

    public static class MyThread extends Thread {

        private CyclicBarrier cyclicBarrier;

        public MyThread(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1 + (new Random().nextInt(10)));
                System.out.println("当前线程：" + Thread.currentThread().getName() + "等待其他线程加载");
                cyclicBarrier.await();
                System.out.println("当前线程：" + Thread.currentThread().getName() + "执行完成");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
